package com.zj.core.net

import android.content.Context
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.zj.core.base.BaseApplication
import com.zj.core.tools.Constant.Companion.wholeUrl
import java.util.Objects
import java.util.concurrent.TimeUnit
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

/**
 * 日期：2019年3月22日
 * 公司：北京子杰宝贝科技有限公司
 * 地址：北京市朝阳区朝阳农场
 * 开发者：达选文
 *
 *
 * 主体功能：Retrofit初始化
 */
class RetrofitClient{
    companion object {
        var retrofit:Retrofit?=null
    }

    fun getInstance(): Retrofit? {
        if(retrofit ==null){
            val mBaseUrl = wholeUrl
            val cookieJar = PersistentCookieJar(SetCookieCache(),
                SharedPrefsCookiePersistor(Objects.requireNonNull<Context>(BaseApplication.context))
            )

            val builder = OkHttpClient.Builder()
            //设置超时
            builder.connectTimeout(15, TimeUnit.SECONDS)
            builder.readTimeout(15, TimeUnit.SECONDS)
            builder.writeTimeout(15, TimeUnit.SECONDS)
            //错误重连
            builder.retryOnConnectionFailure(true)
            //添加cookie
            builder.cookieJar(cookieJar)
            retrofit =Retrofit.Builder()
                .baseUrl(mBaseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build()
        }
        return retrofit
    }
}